import Dep from './dep'

export function observe(data) {
  if (!data || typeof data !== 'object') {
    return
  }
  for (let key in data) {
    let dep = new Dep()
    let val = data[key]
    // 递归
    observe(val)
    Object.defineProperty(data, key, {
      enumerable: true,
      configurable: true,
      get() {
        if (Dep.target) {
          // 添加依赖
          dep.depend()
        }
        return val
      },
      set(newVal) {
        if (val === newVal) return
        val = newVal
        // 通知所有订阅者
        dep.notify()
      }
    })
  }
}